import axios from "axios";
import qs from "qs";
import errorCode from '@/util/errorCodeValues';
import router from '@/router';
import { Toast } from 'mint-ui';

axios.interceptors.response.use(
    response =>{
        if(response.data&&response.data.errorCode){
            for(let key of Object.keys(errorCode)){
                if(key===response.data.errorCode){
                    console.log(`errorCode:${errorCode[key].errorCode};errorMsg:${errorCode[key].errorMsg}`);//注意！！这里不是单引号 '  而是 `
                    Toast({
                        message:errorCode[key].errorMsg,//错误信息
                        duration:1000
                    });
                    if(errorCode[key].route){
                        router.push(errorCode[key].route);
                        return;
                    }else{
                        return response;
                    }
                }
            }
            Toast({
                message:'服务器出现故障...已提交管理员!',//错误信息
                duration:1000
            });
            console.log('interceptors errorCode日志:');
            console.log(response.data);
        }

        return response;
    },
    error => {
        console.log(error);
    }
)

export default {
    //校验是否为手机号
    checkIsMobile(phoneNum) {
        var reg = /^(1[3|4|5|7|8])[\d]{9}$/;
        if (reg.test(phoneNum) == false) {
            return false;
        }
        return true;
    },
    //判断非空
    isValidate(obj) {
        return obj != null && obj != "" && obj != undefined;
    },

    //判断数组
    isValidateArr(arr){
        return arr != null && arr != undefined && arr.length>0;
    },
    //给字符串长度大于一个数字的该字符串后面加上...
    interceptStr(str,num){
        return (this.isValidate(str)&&str.length>num)?str.substring(0,num)+'...':str;
    },

    //将url里的参数解析成json对象
    convertUrlToJSON(urlData){
        let field = urlData.split('&');

        let res = {};
        for(let i=0,len=field.length;i<len;i++){
            let temp = field[i].split('=');
            res[temp[0]]=temp[1];
        }
        return res;
    },

    axiosPost(url, data) {
        axios.create({headers: {'content-type': 'application/x-www-form-urlencoded'}});
        data = qs.stringify(data);
        return axios.post(url, data);
    }
}
